package org.jhotdraw.draw.action;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.JOptionPane;

import org.jhotdraw.draw.Drawing;
import org.jhotdraw.draw.DrawingEditor;
import org.jhotdraw.draw.DrawingView;
import org.jhotdraw.draw.Figure;
import org.jhotdraw.draw.ImageFigure;
import org.jhotdraw.util.ResourceBundleUtil;

public class ApplyThresholdingAction extends AbstractSelectedAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public final static String ID = "edit.applyThresholding";

	/** Creates a new instance. */
	public ApplyThresholdingAction(DrawingEditor editor) {
		super(editor);
		ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.draw.Labels");
		labels.configureAction(this, ID);
		updateEnabledState();
	}

	@Override
	public void actionPerformed(java.awt.event.ActionEvent e) {
		final DrawingView view = getView();
		final LinkedList<Figure> figures = new LinkedList<Figure>(view.getSelectedFigures());
		applyThreshold(view, figures);
	}

	public void applyThreshold(DrawingView view, Collection<Figure> figures) {
		Drawing drawing = view.getDrawing();
		Iterator<Figure> i = drawing.sort(figures).iterator();
		while (i.hasNext()) {
			Figure figure = (Figure) i.next();
			if (figure instanceof ImageFigure) {
				ImageFigure image = (ImageFigure) figure;
				int threshold = -2;
				while ((threshold < 0) || (threshold > 255)) {
					String temp = JOptionPane.showInputDialog(null,"Insert a value between 0-255 to thresholding","Threshold",JOptionPane.QUESTION_MESSAGE);
					threshold = Integer.parseInt(temp);
				}

				image.makeGray();
				image.applyThreshold(threshold);
			}
		}

	}
}
